package com.bot.nft.core.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.bot.nft.core.config.AvataUtils;
import com.bot.nft.core.config.BlockchainUtil;
import java.util.Map;

/**
 * @author zhangkaige
 */
public class ChainRequestUtil {


    //上链post
    public static HttpResponse post(String path, Map<String, Object> query, Map<String, Object> body) {
        HttpRequest post = HttpRequest.post(BlockchainUtil.getDns() + path);
        return request(post, path, query, body);
    }

    //上链get
    public static HttpResponse get(String path, Map<String, Object> query, Map<String, Object> body) {
        HttpRequest post = HttpRequest.get(BlockchainUtil.getDns() + path);
        return request(post, path, query, body);
    }

    //上链delete
    public static HttpResponse delete(String path, Map<String, Object> query, Map<String, Object> body) {
        HttpRequest post = HttpRequest.delete(BlockchainUtil.getDns() + path);
        return request(post, path, query, body);
    }

    private static HttpResponse request(HttpRequest httpRequest, String path, Map<String, Object> query, Map<String, Object> body) {
        //请求时间戳
        long timestamp = System.currentTimeMillis();
        //API Secret
        String apiSecret = BlockchainUtil.getApiSecret();
        //API 签名
        String signature = AvataUtils.signRequest(path, query, body, timestamp, apiSecret);
        return httpRequest.header("Content-Type", "application/json")
                .header("X-Api-Key", BlockchainUtil.getApiKey())
                .header("X-Timestamp", String.valueOf(timestamp))
                .header("X-Signature", signature)
                .body(JSON.toJSONString(body))
                .execute();
    }
}
